﻿using Sgr.Utilities;
using System.Text.Json;
using System.Text.Json.Serialization;

namespace Sgr.Serialization
{
    public class UtcDateTimeNullableConverter : JsonConverter<DateTime?>
    {
        public override DateTime? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
        {
            if (reader.TokenType == JsonTokenType.Null)
                return null;

            var value = reader.GetString();
            if (string.IsNullOrEmpty(value))
                return null;

            return DateTimeHelper.ParseToUtc(value);
        }

        public override void Write(Utf8JsonWriter writer, DateTime? value, JsonSerializerOptions options)
        {
            if (value == null)
            {
                writer.WriteNullValue();
                return;
            }

            //if (value.Value.Kind != DateTimeKind.Utc)
            //    throw new JsonException("DateTime 必须是 UTC 时间.");

            var utc = value.Value.Kind switch
            {
                DateTimeKind.Utc => value.Value,
                DateTimeKind.Local => value.Value.ToUniversalTime(),
                _ => UtcDateTimeConverterInternal.HandleUnspecified(value.Value, assumeLocal: false)
            };

            writer.WriteStringValue(utc);
        }
    }
}